package com.huike.clues.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.huike.clues.service.ISysFileService;
import com.huike.common.core.domain.AjaxResult;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author ethanhu
 */
@Service
@Slf4j
public class SysFileServiceImpl implements ISysFileService{
    private final static String UPLOAD_PATH = "./home/huike/file/";

    @Override
    public AjaxResult<String> upload(MultipartFile file) {
        if (file.getSize() > 1024 * 1024 * 10) {
            return AjaxResult.error("文件大小不能大于10MB");
        }
        String filename = file.getOriginalFilename();
        String newFilename = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/"
                + UUID.randomUUID().toString().replaceAll("-", "")
                + Objects.requireNonNull(filename).substring(filename.lastIndexOf("."));
        try {
            File savePathFile = new File(UPLOAD_PATH + newFilename);
            File newDir = new File(UPLOAD_PATH + newFilename.substring(0, newFilename.lastIndexOf("/")));
            newDir.mkdirs();
            savePathFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("保存文件异常");
        }

        try (
                InputStream inputStream = file.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(UPLOAD_PATH + newFilename);
        ) {
            int len;
            byte[] buffer = new byte[8 * 1024];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("保存文件异常");
        }

        return AjaxResult.success(filename);
    }
}
